///////////////////////////////////////////////////////
/* SIMPLE CHAT
 * - A complete windows dialog-based multi-user chat system with multiple
 * dialogs. Demonstrates the use of a richedit control, ip address control,
 * winsock, listbox, and more.
 *************************************************
 * Made by Mitchell Hashimoto
 * xmitchx@gmail.com
 */
///////////////////////////////////////////////////////
#include "main.h"

/*
 * External Functions
 */
extern BOOL CALLBACK dlgTypeProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
extern BOOL CALLBACK dlgServerProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

/*
 * CenterOnScreen
 * - Center a window in the middle of the WORK AREA
 * The work area is the area of the screen not couning things such as
 * the start/task bar
 */
void CenterOnScreen(HWND hWnd)
{
	RECT rcClient, rcDesktop;

	SystemParametersInfo(SPI_GETWORKAREA, 0, &rcDesktop, 0);
	GetWindowRect(hWnd, &rcClient);

	int nX = ((rcDesktop.right - rcDesktop.left) / 2) -
		((rcClient.right - rcClient.left) / 2);
	int nY = ((rcDesktop.bottom - rcDesktop.top) / 2) -
		((rcClient.bottom - rcClient.top) / 2);

	SetWindowPos(hWnd, NULL, nX, nY, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}

/*
 * EnableMenu
 * - Enable/Disable a Menu Item by item ID
 */
void EnableMenu(HMENU hMenu, UINT menuID, BOOL bEnabled = TRUE)
{
	int nMask = bEnabled ? MF_ENABLED : MF_GRAYED;

	EnableMenuItem(hMenu, menuID, nMask | MF_BYCOMMAND);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	/*
	 * Display initial dialog box to select type (Client or Server)
	 */
	int nRet = DialogBox(hInstance, MAKEINTRESOURCE(IDD_TYPE), NULL, dlgTypeProc);
	if (nRet != 0)
	{
		/*
		 * Client or Server selected.
		 * Load rich edit library (used to display text in both client and server)
		 */
		HINSTANCE hRichEd = LoadLibrary("Riched32.dll");
		
		/*
		 * Init IP Address Common Control
		 */
		INITCOMMONCONTROLSEX commType;
		commType.dwSize = sizeof(commType);
		commType.dwICC = ICC_INTERNET_CLASSES;
		InitCommonControlsEx(&commType);

		/*
		 * dlgReturn is a data structure that returns:
		 * 1. Next dialog ID (dlgID)
		 * 2. Pointer to dialog processing function (lpDlgProc)
		 * 3. Params array containing parameters for next dialog (server name, etc.)
		 */
		dlgReturn *dataReturn = (dlgReturn *)nRet;
		DialogBoxParam(hInstance, MAKEINTRESOURCE(dataReturn->dlgID), NULL, dataReturn->lpDlgProc, (long)dataReturn);

		/*
		 * Clean up!
		 */
		free(dataReturn->params);
		free(dataReturn);

		FreeLibrary(hRichEd);
	}

	return 0;
}